package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
//添加事务
@Transactional(rollbackFor = Exception.class)
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {

    @Autowired
    private EmpExprService empExprService;
    @Override
    public void saveEmp(Emp emp) {
        emp.setPassword("123456");
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        this.save(emp);
        //调用其工作经历
        //判断其工作经历不为空
        List<EmpExpr> exprList = emp.getExprList();
        if (exprList != null && exprList.size() > 0) {
            exprList.forEach(empExpr -> {empExpr.setEmpId(emp.getId());});
        }
        empExprService.saveBatch(exprList);
    }

    @Override
    public Emp  getEmpById(Integer id) {
        //回显数据
        Emp emp = this.getById(id);
        if (emp == null) {
            throw new RuntimeException("该数据不存在");
        }
        //查询工作经历
        List<EmpExpr> list = empExprService.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, id));
        if (list != null && list.size() > 0) {
            emp.setExprList(list);
        }
        return emp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmp(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        this.updateById(emp);
        //删除其工作经历
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId()));
        //拿到修改的工作经历集合
        List<EmpExpr> exprList = emp.getExprList();
        if (exprList != null && exprList.size() > 0) {
            exprList.forEach(empExpr -> {empExpr.setEmpId(emp.getId());});
            empExprService.saveBatch(exprList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeEmpByIds(List<Integer> ids) {
        //删除员工  以及员工经历
        this.removeByIds(ids);
        //删除其工作经历
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId, ids));
    }
}
